package com.hntxk.cqzd.diacrisis.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.io.CharStreams;
import com.hntxk.core.ext.mybatis.adapter.SQLAdapter;
import com.hntxk.core.framework.model.ResponseModel;
import com.hntxk.core.framework.model.ResultModel;
import com.hntxk.core.framework.service.impl.BaseServiceImpl;
import com.hntxk.core.util.DateUtil;
import com.hntxk.core.util.LoggerUtil;
import com.hntxk.core.util.NumberUtil;
import com.hntxk.core.util.StringUtil;
import com.hntxk.cqzd.basicinfo.basepatient.service.BasePatientManageService;
import com.hntxk.cqzd.basicinfo.log.loginterface.model.TblLogInterface;
import com.hntxk.cqzd.basicinfo.log.loginterface.service.InterfacelManageService;
import com.hntxk.cqzd.basicinfo.log.loginterface.service.impl.InterfaceManageServiceImpl;
import com.hntxk.cqzd.common.service.CommonFileService;
import com.hntxk.cqzd.common.util.CalculateAge;
import com.hntxk.cqzd.diacrisis.entity.*;
import com.hntxk.cqzd.diacrisis.model.*;
import com.hntxk.cqzd.diacrisis.model.his.*;
import com.hntxk.cqzd.diacrisis.service.*;
import com.hntxk.sp.dict.manager.DictManager;
import com.hntxk.sp.dict.model.Dict;
import com.hntxk.sp.log.model.ActionLog;
import com.hntxk.sp.log.model.ActionType;
import com.hntxk.sp.util.LogRecordUtil;
import com.hntxk.sp.util.LoginUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.Charsets;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


@Service("diacInfoService")
@Transactional(rollbackFor = Exception.class)
@Slf4j
public class DiacrisisInfoServiceImpl extends BaseServiceImpl<TblDiacrisisInfo> implements DiacrisisInfoService {

    public static String DIACINFO_MAPPER_NAMESPACE="com.hntxk.cqzd.diacrisis.mapper.DiacrisisInfoMapper.";


    private final DiacrisisAssayService assayService;
    private final DiacrisisCardService cardService;
    private final DiacrisisExistingChildService existingChildService;
    private final DiacrisisFetusDetailService fetusDetailService;
    private final DiacrisisFetusService fetusService;
    private final DiacrisisFileService fileService;
    private final DiacrisisLiveService liveService;

    @Autowired
    @Qualifier("commonFileServiceImpl")
    CommonFileService commonFileService;

    @Autowired
    @Qualifier("basePatientService")
    BasePatientManageService basePatientManageService;

    @Autowired
    @Qualifier("LogInterfaceService")
    InterfacelManageService interfacelManageService;

    public DiacrisisInfoServiceImpl(@Qualifier("diacAssayService") DiacrisisAssayService assayService,
                                    @Qualifier("diacCardService") DiacrisisCardService cardService,
                                    @Qualifier("diacExistingChildService") DiacrisisExistingChildService existingChildService,
                                    @Qualifier("diacFetusDetailService") DiacrisisFetusDetailService fetusDetailService,
                                    @Qualifier("diacFetusService") DiacrisisFetusService fetusService,
                                    @Qualifier("diacFileService") DiacrisisFileService fileService,
                                    @Qualifier("diacLiveService") DiacrisisLiveService liveService) {
        super(DIACINFO_MAPPER_NAMESPACE);
        this.assayService = assayService;
        this.cardService = cardService;
        this.existingChildService = existingChildService;
        this.fetusDetailService = fetusDetailService;
        this.fetusService = fetusService;
        this.fileService = fileService;
        this.liveService = liveService;
    }

    @Override
    public TblDiacrisisInfo getById(Long id){
        TblDiacrisisInfo tbl = get(DIACINFO_MAPPER_NAMESPACE + "get", id);
        return tbl;
    }


    /**
     * 手机端新增诊断基本信息
     * @param diacrisisAllModel
     * @param files
     * @throws IOException
     */
    @Override
    public ResultModel<DiacrisisAllModel> insertPhone(DiacrisisAllModel diacrisisAllModel, MultipartFile[] files) throws IOException {
        //设置主键值
        TblDiacrisisInfo tblDiacrisisInfo=diacrisisAllModel.getTblDiacrisisInfo();
        try {
            tblDiacrisisInfo = basePatientManageService.insertPhone(tblDiacrisisInfo);
        } catch (ParseException e) {
            e.printStackTrace();
        }
//        tblDiacrisisInfo.setRecordTime(new Date());
        setSelectName(tblDiacrisisInfo);
        tblDiacrisisInfo.setIsValid('1');
        tblDiacrisisInfo.setCreateUserId((long) -1024);
        tblDiacrisisInfo.setCreateUserName("手机用户");
        tblDiacrisisInfo.setCreateTime(new Date());
        insert(DIACINFO_MAPPER_NAMESPACE + "insert", tblDiacrisisInfo);

        List<TblDiacrisisCard> diacrisisCard = diacrisisAllModel.getDiacrisisCard();
        if(diacrisisCard!=null&&diacrisisCard.size()>0){
            cardService.insert(diacrisisAllModel);
        }
        List<TblDiacrisisExistingChild> existingChild = diacrisisAllModel.getExistingChild();
        if(existingChild!=null&&existingChild.size()>0){
            existingChildService.insert(diacrisisAllModel);
        }
        List<TblDiacrisisLive> patientlive = diacrisisAllModel.getPatientlive();
        if(patientlive!=null&&patientlive.size()>0){
            liveService.insert(diacrisisAllModel);
        }

        /**挂号患者参与诊断信息录入之后  修改his对象的状态值为Y  页面始终查询状态值为N的数据*/
        Long hisId = tblDiacrisisInfo.getHisId();
        if(NumberUtil.isNotNull(hisId)){
            HisModel hisModel = getByHisId(hisId);
            if(hisModel!=null){
                hisModel.setIsBeoperated('Y');
                update(DIACINFO_MAPPER_NAMESPACE+"updateHis",hisModel);
            }
        }

        return ResultModel.empty();
    }




    /**
     * 新增诊断信息
     * @param diacrisisAllModel
     * @param files
     * @throws IOException
     */
    @Override
    public ResultModel<DiacrisisAllModel> insert(DiacrisisAllModel diacrisisAllModel, MultipartFile[] files) throws IOException {
        //设置主键值
        TblDiacrisisInfo tblDiacrisisInfo=diacrisisAllModel.getTblDiacrisisInfo();
        try {
            tblDiacrisisInfo = basePatientManageService.insert(tblDiacrisisInfo);
        } catch (ParseException e) {
            e.printStackTrace();
        }
//        tblDiacrisisInfo.setRecordTime(new Date());
        setSelectName(tblDiacrisisInfo);
        tblDiacrisisInfo.setCreateUserId(LoginUserUtil.getLoginOperatorIdLong());
        tblDiacrisisInfo.setCreateUserName(LoginUserUtil.getLoginUserName());
        Date nowDate = new Date();
        tblDiacrisisInfo.setCreateTime(nowDate);
        tblDiacrisisInfo.setRecordTime(nowDate);

        String year = String.valueOf(DateUtil.getYear(nowDate));
        int month1 = DateUtil.getMonth(nowDate);
        String month = String.valueOf(month1);
        if(month1<10){
            month="0"+month1;
        }
        String recordIdStr =year+month;

        List<String> list = (List<String>) query(DIACINFO_MAPPER_NAMESPACE + "maxRecordId", recordIdStr+"%", 0, 1);
        if(StringUtil.isNull(list.get(0))){
            tblDiacrisisInfo.setRecordId(recordIdStr+"0001");
        }else{
            tblDiacrisisInfo.setRecordId((Long.parseLong(list.get(0))+1)+"");
        }

        super.insert(DIACINFO_MAPPER_NAMESPACE + "insert", tblDiacrisisInfo);

        //如果从表有数据  执行插入
        List<TblDiacrisisAssay> diacrisisAssay = diacrisisAllModel.getDiacrisisAssay();
        if(diacrisisAssay!=null&&diacrisisAssay.size()>0){
            //如果第一条数据的nipt没有值 就不插入所有值
            TblDiacrisisAssay tblDiacrisisAssay = diacrisisAssay.get(0);
            if(NumberUtil.isNotNull(tblDiacrisisAssay.getNiptTypeId()) && NumberUtil.isNotNull(tblDiacrisisAssay.getBloodTypeId())){
                assayService.insert(diacrisisAllModel);
            }
        }
        List<TblDiacrisisCard> diacrisisCard = diacrisisAllModel.getDiacrisisCard();
        if(diacrisisCard!=null&&diacrisisCard.size()>0){
            cardService.insert(diacrisisAllModel);
        }
        List<TblDiacrisisExistingChild> existingChild = diacrisisAllModel.getExistingChild();
        if(existingChild!=null&&existingChild.size()>0){
            existingChildService.insert(diacrisisAllModel);
        }
        List<TblDiacrisisLive> patientlive = diacrisisAllModel.getPatientlive();
        if(patientlive!=null&&patientlive.size()>0){
            liveService.insert(diacrisisAllModel);
        }
        List<FetusAndDetailsModel> diacrisisFetus = diacrisisAllModel.getDiacrisisFetus();
        if(diacrisisFetus!=null&&diacrisisFetus.size()>0){
            fetusService.insert(diacrisisAllModel);
        }

        if(files!=null&&files.length>0){
            //调用上传文件的方法
            commonFileService.upload( DiacrisisFileServiceImpl.DIACFILE_MAPPER_NAMESPACE+"insert",files,diacrisisAllModel.getTblDiacrisisInfo().getDiacrisisId(),"diac");
        }

        /**挂号患者参与诊断信息录入之后  修改his对象的状态值为Y  页面始终查询状态值为N的数据*/
        /*
        Long hisId = tblDiacrisisInfo.getHisId();
        if(NumberUtil.isNotNull(hisId)){
            HisModel hisModel = getByHisId(hisId);
            if(hisModel!=null){
                hisModel.setIsBeoperated('Y');
                update(DIACINFO_MAPPER_NAMESPACE+"updateHis",hisModel);
            }
        }*/

         LogRecordUtil.addLog(new ActionLog(TblDiacrisisInfo.class, tblDiacrisisInfo.getDiacrisisId() + "", "12",
                ActionType.ADD, "新增了诊断基本信息：" + tblDiacrisisInfo.getPatientName() + "[ " + tblDiacrisisInfo.getPatientAddress() + " ]"));
        return ResultModel.empty();
    }

    /**
     * 修改诊断信息数据
     * @param diacrisisAllModel 诊断模型
     * @param files
     * @throws IOException
     */

    @Override
    public ResultModel<DiacrisisAllModel> update(DiacrisisAllModel diacrisisAllModel,MultipartFile[] files) throws IOException{
        setSelectName(diacrisisAllModel.getTblDiacrisisInfo());
        diacrisisAllModel.getTblDiacrisisInfo().setUpdateUserId(LoginUserUtil.getLoginOperatorIdLong());
        diacrisisAllModel.getTblDiacrisisInfo().setUpdateUserName(LoginUserUtil.getLoginUserName());
        diacrisisAllModel.getTblDiacrisisInfo().setUpdateTime(new Date());

        update(DIACINFO_MAPPER_NAMESPACE + "update", diacrisisAllModel.getTblDiacrisisInfo());

        List<TblDiacrisisAssay> diacrisisAssay = diacrisisAllModel.getDiacrisisAssay();
        if(diacrisisAssay!=null&&diacrisisAssay.size()>0){
            assayService.update(diacrisisAllModel);
        }
        List<TblDiacrisisCard> diacrisisCard = diacrisisAllModel.getDiacrisisCard();
        if(diacrisisCard!=null&&diacrisisCard.size()>0){
            ResultModel<DiacrisisAllModel> cardUpdate = cardService.update(diacrisisAllModel);
            if(cardUpdate.hasError()){
                return cardUpdate;
            }
        }
        List<TblDiacrisisExistingChild> existingChild = diacrisisAllModel.getExistingChild();
        if(existingChild!=null&&existingChild.size()>0){
            existingChildService.update(diacrisisAllModel);
        }
        List<TblDiacrisisLive> patientlive = diacrisisAllModel.getPatientlive();
        if(patientlive!=null&&patientlive.size()>0){
            liveService.update(diacrisisAllModel);
        }
        List<FetusAndDetailsModel> diacrisisFetus = diacrisisAllModel.getDiacrisisFetus();
        if(diacrisisFetus!=null&&diacrisisFetus.size()>0){
            fetusService.update(diacrisisAllModel);

        }

        if(files!=null&&files.length>0){
            //调用上传文件的方法
            commonFileService.upload( DiacrisisFileServiceImpl.DIACFILE_MAPPER_NAMESPACE+"insert",files,diacrisisAllModel.getTblDiacrisisInfo().getDiacrisisId(),"diac");
        }
        /*
        LogRecordUtil.addLog(new ActionLog(TblDiacrisisInfo.class, diacrisisAllModel.getTblDiacrisisInfo().getDiacrisisId() + "", "12",
                ActionType.UPDATE, "修改了诊断基本信息：" + diacrisisAllModel.getTblDiacrisisInfo().getPatientName() + "[ " + diacrisisAllModel.getTblDiacrisisInfo().getPatientAddress() + " ]"));
         */
        return ResultModel.empty();

    }

    /**
     * 查询单条诊断信息数据
     * @param id  诊断id
     * @return
     */

    @Override
    public DiacrisisAllModel getDiacrisisInfo(Long id){


        //获取诊断信息表的主键值
        TblDiacrisisInfo info = get(id);


        DiacrisisAllModel model = new DiacrisisAllModel();
        model.setTblDiacrisisInfo(info);
        //查询从表数据
        List<TblDiacrisisAssay> assays = assayService.getByFkId(id);
        List<TblDiacrisisCard> cards = cardService.getByFkId(id);
        List<TblDiacrisisExistingChild> childs = existingChildService.getByFkId(id);
        List<FetusAndDetailsModel> fetuses = fetusService.getByFkId(id);
        List<TblDiacrisisLive> lives = liveService.getByFkId(id);

        List<TblDiacrisisFile> files = fileService.getByFkId(id);
        model.setDiacrisisAssay(assays);
        model.setDiacrisisCard(cards);
        model.setDiacrisisFetus(fetuses);
        model.setExistingChild(childs);
        model.setPatientlive(lives);
        model.setFiles(files);

        return model;
    }

    /**
     * 查询历史诊断数据
     * @param param  身份证/卡号/姓名
     * @param isValid 是否作废
     * @return
     */
    @Override
    public ResponseModel getAllInfo(String param, String isValid) {
        TblDiacrisisInfo tblDiacrisisInfo=new TblDiacrisisInfo();
        if(param!=null&&param!=""){
            tblDiacrisisInfo.setPatientName(param);
        }
        if(isValid!=null&&isValid!=""){
            tblDiacrisisInfo.setIsValid(isValid.charAt(0));
        }

        return  query2Json(DIACINFO_MAPPER_NAMESPACE + "queryAll", tblDiacrisisInfo, true);
    }


    /**
     * 设置诊断对象的基本属性值
     * @param info
     */
    public void setSelectName(TblDiacrisisInfo info){
        if(StringUtil.isNotNull(info.getPatientCardId())){
            //校验身份证
            String regIdCard = "(^\\d{15}$)|(^\\d{18}$)|(^\\d{17}(\\d|X|x)$)";
            boolean b = info.getPatientCardId().matches(regIdCard);
            if(b==false){
                throw new IllegalArgumentException("身份证输入有误");
            }
        }else{
            throw new RuntimeException("请输入身份证");
        }
        getPrimaryKey(info);
        info.setPatientSex('f');
        Long fetusesTypeId = info.getFetusesTypeId();
        if (fetusesTypeId==null||fetusesTypeId==1) {
            info.setFetusesType("单胎");
        }else{
            info.setFetusesType("多胎");
        }

        Long patientRaceId = info.getPatientRaceId();
        //设置民族id值
        if(patientRaceId==null){
            info.setPatientRaceId((long) 1);
        }
        Long patientEduId = info.getPatientEduId(); //患者学历id
        Long spouseEduId = info.getSpouseEduId(); //配偶学历id
        Long patientOccupationId = info.getPatientOccupationId();  //患者职业id
        Long spouseOccupationId = info.getSpouseOccupationId(); //配偶职业id
        if(patientEduId!=null){
            //设置患者学历下拉name
            Dict baseEdu = DictManager.getInstance().getDict("CQ_BASE_EDU", patientEduId);
            info.setPatientEdu(baseEdu.getText());
        }
        if(spouseEduId!=null){
            //设置患者配偶学历下拉name
            Dict spouseEdu = DictManager.getInstance().getDict("CQ_BASE_EDU", spouseEduId);
            info.setSpouseEdu(spouseEdu.getText());
        }

        if(patientOccupationId!=null){
            //设置患者职业下拉name
            Dict baseOccupation = DictManager.getInstance().getDict("CQ_BASE_OCCUPATION", patientOccupationId);
            info.setPatientOccupation(baseOccupation.getText());
        }

        if(spouseOccupationId!=null){
            //设置配偶职业下拉name
            Dict spouseOccupationIdDict = DictManager.getInstance().getDict("CQ_BASE_OCCUPATION", spouseOccupationId);
            info.setSpouseOccupation(spouseOccupationIdDict.getText());
        }

        Long patientReligionId = info.getPatientReligionId(); //宗教信仰
        if (patientReligionId!=null) {
            //设置宗教信仰下拉name
            Dict baseReligion = DictManager.getInstance().getDict("CQ_BASE_RELIGION", patientReligionId);
            info.setPatientReligion(baseReligion.getText());
        }
        Long impgTypeId = info.getImpgTypeId(); //受孕方式
        if (impgTypeId!=null) {
            Dict impgType = DictManager.getInstance().getDict("CQ_BASE_IMPG_TYPE", impgTypeId);
            info.setImpgTypeName(impgType.getText());
        }

        String badGestId = info.getBadGestId();
        if (StringUtil.isNotNull(badGestId)) {
            String badGestName = CalculateAge.idToName(badGestId, "CQ_BASE_BAD_GEST");
            //设置不良孕产史下拉name
            info.setBadGest(badGestName);
        }

        String specialMedicalId = info.getSpecialMedicalId();
        if (StringUtil.isNotNull(specialMedicalId)) {
            //设置特殊病史
            String baseSpecialMedicalName = CalculateAge.idToName(specialMedicalId, "CQ_BASE_SPECIAL_MEDICAL");
            info.setSpecialMedical(baseSpecialMedicalName);
        }
        String drugUseId = info.getDrugUseId();
        if (StringUtil.isNotNull(drugUseId)) {
            //设置孕期用药史下拉name
//            Dict baseDrugUse = DictManager.getInstance().getDict("CQ_BASE_DRUG_USE", drugUseId);
            String baseDrugUseName = CalculateAge.idToName(drugUseId, "CQ_BASE_DRUG_USE");
            info.setDrugUse(baseDrugUseName);
        }

        Long bespeakId = info.getBespeakId();
        if (bespeakId!=null) {
            //设置预约内容下拉name
            Dict bespeakContent = DictManager.getInstance().getDict("CQ_BASE_BESPEAK_CONTENT", bespeakId);
            info.setBespeakContent(bespeakContent.getText());
        }

        String patientTel = info.getPatientTel();
        if(patientTel==null || patientTel=="" ||"".equals(patientTel)) {

        }else{
            //校验电话号码
            String tel = "(^(0\\d{2,3}-\\d{7,8}))|(^1[3456789]\\d{9}$)";
            boolean matches = patientTel.matches(tel);
            if (!matches) {
                throw new IllegalArgumentException("电话号码输入有误");
            }
        }

        String spouseTel = info.getSpouseTel();
        if(spouseTel==null || spouseTel=="" ||"".equals(spouseTel)) {

        }else{
            //校验电话号码
            String tel = "(^(0\\d{2,3}-\\d{7,8}))|(^1[3456789]\\d{9}$)";
            boolean matches = spouseTel.matches(tel);
            if (!matches) {
                throw new IllegalArgumentException("电话号码输入有误");
            }
        }


    }

    /**
     * 根据患者his表主键id查询his单个对象回显
     * @param id
     * @return
     */
    @Override
    public HisModel getByHisId(Long id) {
        HisModel model=new HisModel();
        model.setHisId(id);
        return get(DIACINFO_MAPPER_NAMESPACE + "getByHisId", model);
    }

    /**
     * 手机端根据患者卡号查询his单个对象值
     * @param id
     * @return
     */
    @Override
    public HisModel getByCardCode(String id) {
        /**
         * 添加查询条件
         * 手机端查询30天内未处理的某患者挂号数据
         */
        HisModel model=new HisModel();
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        Date startDate = DateUtils.addDays(new Date(), -30);
        model.setStartDate(DateUtil.getDate(simpleDateFormat.format(startDate)));
        model.setEndDate(DateUtil.getDate(simpleDateFormat.format(new Date())));
        model.setCardCode(id);
        model.setIsBeoperated('N');
        List<HisModel> list = (List<HisModel>) query(DIACINFO_MAPPER_NAMESPACE + "getByCardCode", model);
        if(!list.isEmpty()){
            return list.get(0);
        }
        return null;
    }


    /**
     * 定时请求his数据
     * @return
     */
    public  List<HisModel> getHis(){
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //获取库中最新一条数据的挂号时间
        List<HisModel> modelList = (List<HisModel>) query(DIACINFO_MAPPER_NAMESPACE + "getHisRegisterTime", new HisModel());

        //避免数据丢失   将获取到的数据库中最新一条数据的挂号时间  减一分钟
        Date registerTime = modelList.get(0).getRegisterTime();
        //日期分钟加减
        Calendar calendar=Calendar.getInstance();
        calendar.setTime(registerTime);
        calendar.set(Calendar.MINUTE,calendar.get(Calendar.MINUTE)-1);
        Date calendarTime = calendar.getTime();

        String registerTimeStr = simpleDateFormat.format(calendarTime);

        //获取当前时间
        Date endDate=new Date();
        String endTime = simpleDateFormat.format(endDate);
         endTime = endTime.replace(" ", "T");

         //库中最新一条数据的挂号时间
        registerTimeStr = registerTimeStr.replace(" ", "T");
        //查询五分钟内的his数据
//        String uri="http://192.168.10.175:7800/EncounterPoint/fhir/Appointment?visitTypeCode=01&startTime=2019-11-18T11:40:25&endTime=2019-11-18T12:00:25";
        String uri = "http://192.168.10.175:7801/EncounterPoint/fhir/Appointment?visitTypeCode=01&startTime="+registerTimeStr+"&endTime="+endTime;
//        String uri = "http://192.168.10.175:7801/EncounterPoint/fhir/Appointment?visitTypeCode=01&registrationDeptCode=0062&startTime="+registerTimeStr+"&endTime="+endTime;
//        String uri = "http://192.168.10.175:7801/EncounterPoint/fhir/Appointment?visitTypeCode=01&registrationDeptCode=0062&startTime=2020-01-14T00:00:01&endTime=2020-01-14T17:00:01";

        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(uri);
            // 添加http头信息
//            Date businessTime = new Date(); // 业务时间，查询接口可不填
            Date operationTime = new Date(); // 调用此接口的系统时间，一般是调用平台接口时new当时时间
            httpGet.addHeader("Content-Type", "application/fhir+json");

            httpGet.addHeader("rootId", UUID.randomUUID().toString()); // 调用方存储日志的id，用于追溯日志
            httpGet.addHeader("token", "0000000378"); // 调用接口中的业务号，例如使用患者流水号查询检验报告接口，此处填写患者就诊流水号
            httpGet.addHeader("businessTime", ""); // 此接口对应的业务时间，如果是查询接口可不填
            httpGet.addHeader("domain", "CHANQIANZD"); // 调用此接口的系统域，例如LIS、HIS、SPD
            httpGet.addHeader("key", "ad0ce7db-40d9-4d85-8839-62c3b438aba3"); // 调用此接口的授权码，与系统域对应，一般是总线维护的授权码
            httpGet.addHeader("operationTime", DateUtil.getStrByFormat( operationTime,"yyyy-MM-dd HH:mm:ss")); // 调用此接口的系统时间，一般是调用平台接口时new当时时间
            HttpResponse response;
            response = httpclient.execute(httpGet);

            // 检验状态码，如果成功接收数据
            InputStream out = response.getEntity().getContent();
            String result = CharStreams.toString(new InputStreamReader(out, Charsets.UTF_8));
//            List<HisModel> hisModels=new ArrayList<>();

            //解析数据
            JSONObject jsonObject = JSON.parseObject(result);
            JSONArray entry = (JSONArray) jsonObject.get("entry");
            if(entry!=null&&entry.size()>0) {
                for (int i = 0; i < entry.size(); i++) {
                    HisModel hisModel=new HisModel();
                    JSONObject object = (JSONObject) entry.get(i);
                    if(object!=null) {
                        JSONObject entryJson = (JSONObject) object.get("resource");
                        if (entryJson != null) {
                            Resource resource = JSON.parseObject(entryJson.toJSONString(), Resource.class);
                            if (resource != null) {
//                                if(!"0062".equals(resource.getSpecialty().get(0).getCoding().get(0).getCode())){
//                                    continue;
//                                }
                                Date start = resource.getStart();
                                if(start!=null){
                                    //设置挂号时间
                                    hisModel.setRegisterTime(start);

                                    //设置挂号日期  作为查询条件
                                    SimpleDateFormat simpleDateFormat1=new SimpleDateFormat("yyyy-MM-dd");
                                    hisModel.setRegisterDate(DateUtil.getDate(simpleDateFormat1.format(start)));
                                }
                                //获取his的诊疗流水号  设置为门诊号
                                List<Identifier> identifier = resource.getIdentifier();
                                if(identifier!=null&&identifier.size()>0){
                                    String value = identifier.get(0).getValue();
                                    if(StringUtil.isNotNull(value)){
                                        hisModel.setOutpatientNo(value);
                                    }
                                }

                                for (int j = 0; j < resource.getParticipant().size(); j++) {
                                    Actor actor = resource.getParticipant().get(j).getActor();
                                    if (actor != null) {
                                        List<Extension> extensions = actor.getExtension();
                                        if(extensions!=null&&extensions.size()>0) {
                                            for (int k = 0; k < extensions.size(); k++) {
                                                if (extensions.get(k).getUrl().indexOf("patientName") != -1) {
                                                    hisModel.setPatientName(extensions.get(k).getValueString());
                                                }
                                                if (extensions.get(k).getUrl().indexOf("patientLocalId") != -1) {
                                                    hisModel.setPatientId(extensions.get(k).getValueString());
                                                }
                                                if (extensions.get(k).getUrl().indexOf("Appointment/card") != -1) {
                                                    ValueCodeableConcept valueCodeableConcept = extensions.get(k).getValueCodeableConcept();
                                                    //获取并设置卡信息
                                                    hisModel.setCardTypeId(valueCodeableConcept.getCoding().get(0).getCode());
                                                    hisModel.setCardType(valueCodeableConcept.getCoding().get(0).getDisplay());
                                                    hisModel.setCardCode(valueCodeableConcept.getText());
                                                }
                                                if (extensions.get(k).getUrl().indexOf("Appointment/birthday") != -1) {
                                                    hisModel.setPatientBirthday(extensions.get(k).getValueDateTime());
                                                    Date patientBirthday = hisModel.getPatientBirthday();
                                                    int ageByBirth = CalculateAge.getAgeByBirth(patientBirthday);
                                                    hisModel.setPatientAge(ageByBirth);
                                                }
                                                //设置身份证
                                                if (extensions.get(k).getUrl().indexOf("Appointment/idNo") != -1) {
                                                    hisModel.setPatientCardId(extensions.get(k).getValueString());
                                                }

                                            }

                                        }
                                    }

                                }
                            }
                        }
                    }
                    int count=0;
                    if(StringUtil.isNotNull(hisModel.getPatientId())){
                        /**
                         * 查询his表中是否已经存在未处理的该患者
                         * 如果没有,插入新数据,如果有 找出来修改数据
                         * 确保表中有且只有一条未处理的患者挂号数据
                         * 每次查询新入挂号需要带上未处理这一条件
                         */
                        hisModel.setIsBeoperated('N');
                        count = super.count(DIACINFO_MAPPER_NAMESPACE + "countHis", hisModel);
                    }
                    if(count==0){
                            Object primaryKey = getPrimaryKey(hisModel);
                            hisModel.setHisId((Long) primaryKey);
                            insert(DIACINFO_MAPPER_NAMESPACE+"insertHis",hisModel);
                    }
                    if(count==1){
                        HisModel hisModel1  = get(DIACINFO_MAPPER_NAMESPACE + "getByPatientId", hisModel);
                        Long hisId = hisModel1.getHisId();
                        hisModel.setHisId(hisId);
                        update(DIACINFO_MAPPER_NAMESPACE + "updateAllHis", hisModel);
                    }

//                    hisModels.add(hisModel);
                }

            }

            int code = response.getStatusLine().getStatusCode();
            System.out.println("code:" + code);
        } catch (Exception e) {
            log.error("his接口错误,"+e.getMessage());
        }
        return null;
    }


    @Override
    public  void deleteOneWeek(){
        HisModel model = new HisModel();
        model.setRegisterDate(DateUtil.addDays(new Date(),-7));
       super.delete(DIACINFO_MAPPER_NAMESPACE+"deleteBfOneWeek", model);

    }

    @Override
    public String getByCode(String code, String date) {
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //获取当前时间
        Date endDate=new Date();
        String endTime = simpleDateFormat.format(endDate);

        String startTime = date;

        endTime = endTime.replace(" ", "T");
        startTime = startTime.replace(" ", "T");
        String code1 = null;
        //库中最新一条数据的挂号时间
        String registerTimeStr = startTime.replace(" ", "T");
        //查询五分钟内的his数据
//        String uri="http://192.168.10.175:7800/EncounterPoint/fhir/Appointment?visitTypeCode=01&startTime=2019-11-18T11:40:25&endTime=2019-11-18T12:00:25";
        String uri = "http://192.168.10.175:7801/EncounterPoint/fhir/Appointment?visitTypeCode=01&startTime="+registerTimeStr+"&endTime="+endTime+"&visitNo="+code;
//        String uri = "http://192.168.10.175:7801/EncounterPoint/fhir/Appointment?visitTypeCode=01&registrationDeptCode=0062&startTime="+registerTimeStr+"&endTime="+endTime;
//        String uri = "http://192.168.10.175:7801/EncounterPoint/fhir/Appointment?visitTypeCode=01&registrationDeptCode=0062&startTime=2020-01-14T00:00:01&endTime=2020-01-14T17:00:01";

        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(uri);
            // 添加http头信息
//            Date businessTime = new Date(); // 业务时间，查询接口可不填
            Date operationTime = new Date(); // 调用此接口的系统时间，一般是调用平台接口时new当时时间
            httpGet.addHeader("Content-Type", "application/fhir+json");

            httpGet.addHeader("rootId", UUID.randomUUID().toString()); // 调用方存储日志的id，用于追溯日志
            httpGet.addHeader("token", "0000000378"); // 调用接口中的业务号，例如使用患者流水号查询检验报告接口，此处填写患者就诊流水号
            httpGet.addHeader("businessTime", ""); // 此接口对应的业务时间，如果是查询接口可不填
            httpGet.addHeader("domain", "CHANQIANZD"); // 调用此接口的系统域，例如LIS、HIS、SPD
            httpGet.addHeader("key", "ad0ce7db-40d9-4d85-8839-62c3b438aba3"); // 调用此接口的授权码，与系统域对应，一般是总线维护的授权码
            httpGet.addHeader("operationTime", DateUtil.getStrByFormat( operationTime,"yyyy-MM-dd HH:mm:ss")); // 调用此接口的系统时间，一般是调用平台接口时new当时时间
            HttpResponse response;
            response = httpclient.execute(httpGet);

            // 检验状态码，如果成功接收数据
            InputStream out = response.getEntity().getContent();
            String result = CharStreams.toString(new InputStreamReader(out, Charsets.UTF_8));
//            List<HisModel> hisModels=new ArrayList<>();

            //解析数据
            JSONObject jsonObject = JSON.parseObject(result);
            JSONArray entry = (JSONArray) jsonObject.get("entry");
            if(entry!=null&&entry.size()>0) {
                for (int i = 0; i < entry.size(); i++) {
                    HisModel hisModel=new HisModel();
                    JSONObject object = (JSONObject) entry.get(i);
                    if(object!=null) {
                        JSONObject entryJson = (JSONObject) object.get("resource");
                        if (entryJson != null) {
                            Resource resource = JSON.parseObject(entryJson.toJSONString(), Resource.class);
                            if (resource != null) {
                                code1 = resource.getSpecialty().get(0).getCoding().get(0).getCode();
//                                if(!"0062".equals(resource.getSpecialty().get(0).getCoding().get(0).getCode())){
//                                    continue;
//                                }
                                Date start = resource.getStart();
                                if(start!=null){
                                    //设置挂号时间
                                    hisModel.setRegisterTime(start);

                                    //设置挂号日期  作为查询条件
                                    SimpleDateFormat simpleDateFormat1=new SimpleDateFormat("yyyy-MM-dd");
                                    hisModel.setRegisterDate(DateUtil.getDate(simpleDateFormat1.format(start)));
                                }
                                //获取his的诊疗流水号  设置为门诊号
                                List<Identifier> identifier = resource.getIdentifier();
                                if(identifier!=null&&identifier.size()>0){
                                    String value = identifier.get(0).getValue();
                                    if(StringUtil.isNotNull(value)){
                                        hisModel.setOutpatientNo(value);
                                    }
                                }

                                for (int j = 0; j < resource.getParticipant().size(); j++) {
                                    Actor actor = resource.getParticipant().get(j).getActor();
                                    if (actor != null) {
                                        List<Extension> extensions = actor.getExtension();
                                        if(extensions!=null&&extensions.size()>0) {
                                            for (int k = 0; k < extensions.size(); k++) {
                                                if (extensions.get(k).getUrl().indexOf("patientName") != -1) {
                                                    hisModel.setPatientName(extensions.get(k).getValueString());
                                                }
                                                if (extensions.get(k).getUrl().indexOf("patientLocalId") != -1) {
                                                    hisModel.setPatientId(extensions.get(k).getValueString());
                                                }
                                                if (extensions.get(k).getUrl().indexOf("Appointment/card") != -1) {
                                                    ValueCodeableConcept valueCodeableConcept = extensions.get(k).getValueCodeableConcept();
                                                    //获取并设置卡信息
                                                    hisModel.setCardTypeId(valueCodeableConcept.getCoding().get(0).getCode());
                                                    hisModel.setCardType(valueCodeableConcept.getCoding().get(0).getDisplay());
                                                    hisModel.setCardCode(valueCodeableConcept.getText());
                                                }
                                                if (extensions.get(k).getUrl().indexOf("Appointment/birthday") != -1) {
                                                    hisModel.setPatientBirthday(extensions.get(k).getValueDateTime());
                                                    Date patientBirthday = hisModel.getPatientBirthday();
                                                    int ageByBirth = CalculateAge.getAgeByBirth(patientBirthday);
                                                    hisModel.setPatientAge(ageByBirth);
                                                }
                                                //设置身份证
                                                if (extensions.get(k).getUrl().indexOf("Appointment/idNo") != -1) {
                                                    hisModel.setPatientCardId(extensions.get(k).getValueString());
                                                }

                                            }

                                        }
                                    }

                                }
                            }
                        }
                    }
                    int count=0;
                    if(StringUtil.isNotNull(hisModel.getPatientId())){
                        /**
                         * 查询his表中是否已经存在未处理的该患者
                         * 如果没有,插入新数据,如果有 找出来修改数据
                         * 确保表中有且只有一条未处理的患者挂号数据
                         * 每次查询新入挂号需要带上未处理这一条件
                         */
                        hisModel.setIsBeoperated('N');
                        count = super.count(DIACINFO_MAPPER_NAMESPACE + "countHis", hisModel);
                    }
                    if(count==0){
                        Object primaryKey = getPrimaryKey(hisModel);
                        hisModel.setHisId((Long) primaryKey);
                        insert(DIACINFO_MAPPER_NAMESPACE+"insertHis",hisModel);
                        log.info("his接口额外添加"+hisModel.getPatientName()+":::visitNo为:"+code+"科室编号为："+code1);
                    }
                    if(count==1){
                        HisModel hisModel1  = get(DIACINFO_MAPPER_NAMESPACE + "getByPatientId", hisModel);
                        Long hisId = hisModel1.getHisId();
                        hisModel.setHisId(hisId);
                        update(DIACINFO_MAPPER_NAMESPACE + "updateAllHis", hisModel);
                        log.info("his接口额外更新"+hisModel.getPatientName()+":::visitNo为:"+code+"科室编号为："+code1);
                    }

//                    hisModels.add(hisModel);
                }

            }

//            int codee = response.getStatusLine().getStatusCode();
//            TblLogInterface tblLogInterface=new TblLogInterface();
//            getPrimaryKey(tblLogInterface);
//            tblLogInterface.set
//            interfacelManageService.insert();
            System.out.println("code:" + code);
//            return  hisModels;
        } catch (Exception e) {
            log.error("备用his接口错误,"+e.getMessage());
        }
        return null;
    }

}
